package top.scsoul.voes.web.controller.common;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.scsoul.voes.common.core.domain.AjaxResult;
import top.scsoul.voes.framework.web.service.UserLoginService;

import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

@CrossOrigin
@RestController
public class CaptchaController {

    @Autowired
    UserLoginService userLoginService;

    Integer captchaOutTime = 1000 * 60 * 2;

    @RequestMapping("api/captcha")
    public AjaxResult captcha() throws IOException {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(130, 40, 4, 4);
        String code = captcha.getCode();
        RenderedImage image = (RenderedImage) captcha.createImage(code);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", byteArrayOutputStream);
        String base64Src = "data:image/jpg;base64," + Base64Encoder.encode(byteArrayOutputStream.toByteArray());
        HashMap<String, Object> map = new HashMap<>();
        String uuid = IdUtil.randomUUID();
        map.put("captchaKey", uuid);
        map.put("captcha", base64Src);
        //缓存
        Map<String, String> cacheMap = userLoginService.getCacheMap();
        cacheMap.put(uuid, code);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                cacheMap.remove(uuid);
            }
        }, captchaOutTime);
        return AjaxResult.success(map);
    }
}
